<?php
/**
 * Created by b17
 * 2/27/12 6:52 PM
 */

namespace Managers;

class Category extends BaseManager
{
    const TABLE = '\Catalog\Category';
    protected $__table = self::TABLE;

    protected function createQueryBuilder()
    {
        $qb = parent::createQueryBuilder()
            ->select('c')
            ->from($this->__table, 'c')
            ->andWhere('c.isDel = 0');
        return $qb;
    }

    public function getList()
    {
        $qb = $this->createQueryBuilder();
        $res = $qb->getQuery()->getArrayResult();
        return $res;
    }

    protected function addSubCategories($categories)
    {
        if (!count($categories)) {
            return $categories;
        }
        $subcatManager = new SubCategory();
        $subcats = $subcatManager->getByCategories($categories);
        foreach ($categories as &$category) {
            $category['children'] = array();
            foreach ($subcats as $subcat) {
                if ($subcat['category']['id'] == $category['id']) {
                    $category['children'][] = $subcat;
                }
            }
        }
        return $categories;
    }

    public function getListWithChildren()
    {
        $res = $this->getList();
        $res = $this->addSubCategories($res);
        return $res;
    }

    public function getById($id)
    {
        $qb = $this->createQueryBuilder()
            ->andWhere('c.id = :id')->setParameter('id', $id);
        $res = $qb->getQuery()->getArrayResult();

        return count($res) ? $res[0] : false;
    }

}
